package com.app.service.authority;
import com.app.entity.Pagination;
import com.app.entity.authority.Staff;
import com.app.entity.authority.Department;
import com.app.entity.authority.Role;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.app.mapper.authority.StaffMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.util.List;
import java.io.File;

@Service
public class StaffService {
    private final static Logger logger = LoggerFactory.getLogger(StaffService.class);

    @Autowired
    StaffMapper StaffMapper;


    public Pagination QueryStaffAll(Pagination page) {
        logger.info("func:QueryStaffAll%nparntId:"+page);

        if(page.getOrderName()==null){
            page.setOrderName("MODIFYTIME");
        }
        if(page.getOrderKind()==null){
            page.setOrderKind("desc");
        }
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr="";
        String searchName ="";
        String searchID=null;
        if(page.getSearchData()!=null){
            try{
                jsonStr=  mapper.writeValueAsString(page.getSearchData());
                Department r = mapper.readValue(jsonStr,Department.class);
                searchName=r.getName();
            }
            catch (Exception e){
                logger.error("func:QueryStaffAll jsonStr:"+jsonStr+" "+e.getMessage());
            }
        }


        List<Staff> list = StaffMapper.getList(page.getCurrentItem()-1,page.getPageSize(),searchName,searchID,page.getOrderName(),page.getOrderKind());
        logger.info("" + list);
        page.setData(list);


        page.setTotalItems(StaffMapper.getListSize(page.getCurrentItem(),page.getPageSize(),searchName,searchID));

        return  page;
    }
    public Pagination getInfoDepartID(Pagination page)
    {
        if(page.getOrderName()==null){
            page.setOrderName("MODIFYTIME");
        }
        if(page.getOrderKind()==null){
            page.setOrderKind("desc");
        }
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr="";
        String searchName =null;
        String searchID="";
        if(page.getSearchData()!=null){
            try{
                jsonStr=  mapper.writeValueAsString(page.getSearchData());
                Department r = mapper.readValue(jsonStr,Department.class);
                searchID=r.getId();
            }
            catch (Exception e){
                logger.error("func:getInfoDepartID jsonStr:"+jsonStr+" "+e.getMessage());
            }
        }

        List<Staff> list = StaffMapper.getList(page.getCurrentItem()-1,page.getPageSize(),searchName,searchID,page.getOrderName(),page.getOrderKind());
        logger.info("" + list);
        page.setData(list);

        page.setTotalItems(StaffMapper.getListSize(page.getCurrentItem(),page.getPageSize(),searchName,searchID));
        return page;
    }

    ///上传头像
    public boolean saveImg(String fileName,MultipartFile mfile ) throws Exception
    {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        File upload = new File(path.getAbsolutePath(),"assets/img/");
        if(!upload.exists()) upload.mkdirs();
        //System.out.println("upload url:"+upload.getAbsolutePath());
        String filePath=upload.getAbsolutePath();
        File uploadDir = new  File(filePath);
        //创建一个目录 （它的路径名由当前 File 对象指定，包括任一必须的父路径。）
        if (!uploadDir.exists()) uploadDir.mkdirs();

        File uploadfile = new  File(uploadDir+"/"+  fileName);
        if (uploadfile.exists())   uploadfile.delete();

        mfile.transferTo(uploadfile);

        return true;
    }

    //增
    public int insertStaff(Staff _staff) {
        logger.info("func:insertStaff %n _staff:" + _staff.toString());
        if(_staff.getSelectedArray()!=null)
        {
            String[] strs=_staff.getSelectedArray().split(",");
            if(strs.length>0) {
                for (int i = 0; i < strs.length; i++) {
                    _staff.setRoleId(strs[i]);
                    _staff.setUserId(java.util.UUID.randomUUID().toString());
                    int j = StaffMapper.InsertRole(_staff);
                }
            }else {
                String RoleId=_staff.getSelectedArray();
                _staff.setRoleId(RoleId);
                _staff.setUserId(java.util.UUID.randomUUID().toString());
                int j = StaffMapper.InsertRole(_staff);
            }
        }
        return StaffMapper.insertStaff(_staff);
    }
    //删
    public int DeleteStaffInfo(Staff _staff)
    {
        logger.info("func:DeleteStaffInfo %n parntId:"+_staff);
        int p = StaffMapper.DeleteStaffInfo(_staff);
        return p;
    }

    public List<Staff> getModifyInfo(Staff _staff)
    {
        logger.info("func:getModifyInfo %n _staff:" + _staff);
        List<Staff> dList = StaffMapper.getModifyInfo(_staff);
        for(Staff staff:dList){
            List<Staff> list = staff.getChildren();
            String str = "";
            for(Staff staff1:list)
            {
                if(str.length()<=0){
                    str = staff1.getRoleId();
                }else{
                    str += ","+ staff1.getRoleId();
                }
            }
            staff.setSelectedArray(str);
        }
        return dList;
    }
    @Transactional
    public int UpdateStaffInfo(Staff _staff)
    {
        logger.info("func:UpdateStaffInfo %n _staff:" + _staff);
        if(_staff.getSelectedArray()!=null)
        {
            int k=StaffMapper.deleteRole(_staff.getId());
            String[] strs=_staff.getSelectedArray().split(",");
            if(strs.length>0) {
                for (int i = 0; i < strs.length; i++) {
                    _staff.setRoleId(strs[i]);
                    _staff.setUserId(java.util.UUID.randomUUID().toString());
                    int j = StaffMapper.InsertRole(_staff);
                }
            }else {
                String RoleId=_staff.getSelectedArray();
                _staff.setRoleId(RoleId);
                _staff.setUserId(java.util.UUID.randomUUID().toString());
                int j = StaffMapper.InsertRole(_staff);
            }
        }
        int p = StaffMapper.UpdateStaffInfo(_staff);
        return p;
    }
    public  List<Staff> getInfoByDepartId(String DepartId)
    {
        logger.info("func:getInfoByDepartId %n DepartId:" + DepartId);
        List<Staff> list = StaffMapper.getInfoByDepartId(DepartId);
        return list;
    }
    public  List<Role> getFormInfo(Staff _staff)
    {
        logger.info("func:getFormInfo %n _staff:" + _staff);
        List<Role> list = StaffMapper.getFormInfo(_staff);
        return list;
    }

    public  List<Staff> StaffNumberInfo(Staff _staff)
    {
        logger.info("func:getFormInfo %n _staff:" + _staff);
        List<Staff> list = StaffMapper.StaffNumberInfo(_staff);
        return list;
    }
}
